/*
 *  Copyright (C) 2011 glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.balisunrise.nbpam.windows;

import java.util.logging.Logger;
import javax.swing.JPanel;
import org.balisunrise.common.VisualEntity;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.ImageUtilities;

/**
 * Top Componente padrão que representa uma View da Aplicativo.
 * 
 * @author glauco
 */
public abstract class AbstractTopComponentView<T extends VisualEntity<JPanel>>
        extends TopComponent
        implements TopComponentView{

    /**
     * Instância padrão
     */
    protected static AbstractTopComponentView instance;

    /**
     * ID padrão.
     */
    protected static final String PREFERRED_ID =
            "AbstractTopComponentViewTopComponent";

    /**
     * Entidade Visual.
     */
    protected  T visualEntity;

    /**
     * Flag que define se a View foi comfirmado ou não.
     * O valor padrão é null, pois nem todas View possuem esta opção.
     * @see #getConfirmation()
     */
    protected Boolean confirmation = null;;

    /**
     * Icone da View
     */
    protected String iconPath = "org/balisunrise/nbpam/view/detailed1.png";

    public AbstractTopComponentView(T visualEntity){
        this.visualEntity = visualEntity;
        init();
        init2();
        setName(visualEntity.getTitle());
        setToolTipText(visualEntity.getTitle());
    }

    public AbstractTopComponentView() {
        initComponents();
        setName("View");
        setToolTipText("Not Defined View.");
        init2();
    }

    private void init(){
        
        JPanel panel = visualEntity.getVisualRepresentation();

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        //this.repaint();
    }

    private void init2(){
        setIcon(ImageUtilities.loadImage(iconPath, true));
        putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized AbstractTopComponentView getDefault() {
        if (instance == null) {
            instance = new AbstractTopComponentView() {

                @Override
                public Boolean getConfirmation() {
                    return null;
                }
            };
        }
        return instance;
    }

    /**
     * Obtain the AbstractTopComponentView instance.
     * Never call {@link #getDefault} directly!
     */
    public static synchronized AbstractTopComponentView findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(AbstractTopComponentView.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof AbstractTopComponentView) {
            return (AbstractTopComponentView) win;
        }
        Logger.getLogger(AbstractTopComponentView.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        
    }

    @Override
    public void componentClosed() {
        
    }

    public void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    public Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    protected void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    @Override
    protected String preferredID() {
        return visualEntity.getName();
    }

    /**
     * Representação Visual. O próprio TopComponent.
     */
    @Override
    public TopComponent getVisualRepresentation() {
        return this;
    }

    /**
     * Retorna a VisualEntity desta View.
     */
    @Override
    public VisualEntity getVisualEntity() {
        return visualEntity;
    }

    /**
     * Algumas View podem retornar ao confirmar ou cancelar, se for uma destas
     * é retornado um objeto Boolean informando se foi confirmado.
     * Quando as View não retornam ao confirmar, é retornado nulo.
     *
     * @return <code>true</code> se foi confirmada a View, <code>false</code>
     * caso contrário e <code>null</code> caso a confirmação da View não
     * termina a exibição.
     */
    @Override
    public Boolean getConfirmation(){
        return confirmation;
    }
}
